package com.UnionPayCenter.vastchain;

import com.UnionPayCenter.exception.ApiException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * @program: vctc-demo
 * @description: 短信
 * @author: bite
 * @create: 2019-05-29 13:43
 **/
@Slf4j
public class SmsUtil {

    private static MediaType MEDIA_TYPE = MediaType.parse("application/json");
    /*
        post方式
     */
    private static final String METHOD_POST = "POST";
    /*
        发送验证码url
     */
    private static final String PATH_VERIFICATION_CODE = "/sms/verificationCode";

    /**
     * 发送验证码短信
     *
     * @param code
     * @param mobile
     */
    public static void sendVerificationCodeMsg(String code, String mobile) {
        try {
            //封装body
            // 目前只支持同时发送 1 条短信
            JSONObject itemJson = new JSONObject();
            // 国内短信：11位手机号码，例如15951955195; 国际/港澳台消息：国际区号+号码，例如85200000000
            itemJson.put("phoneNumbers", mobile);
            // 验证码类型，目前只支持整数
            itemJson.put("codeType", "integer");
            // 短信验证码
            itemJson.put("code", code);
            JSONArray items = new JSONArray();
            items.add(itemJson);
            JSONObject body = new JSONObject();
            body.put("items", items);

            SigningResult result = Signature.sign(METHOD_POST, PATH_VERIFICATION_CODE, "", body.toJSONString());

            OkHttpClient client = new OkHttpClient();
            Request.Builder request = new Request.Builder();

            if (METHOD_POST.equals("GET")) {
                request = request.get();
            } else {
                request = request.post(RequestBody.create(MEDIA_TYPE, body.toJSONString()));
            }

            Request build = request
                    .url(result.fullUri)
                    .build();

            Response response = client.newCall(build).execute();

            String res = response.body().string();
            log.info("sendVerificationCodeMsg response {}", res);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String status = jsonObject.getString("status");

            if (status.equals("success") || status.equals("pending")) {
                return; // 成功
            }
            if("E19A0001".equals(jsonObject.getString("code"))){
                throw new ApiException(-1, "当日短信发送次数过多");
            }
            throw new ApiException(-1, jsonObject.getString("msg"));
        }catch (ApiException e){
            log.error(String.format("短信验证码发送失败，手机号：%s", mobile), e);
            throw new ApiException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(String.format("短信验证码发送失败，手机号：%s", mobile), e);
            throw new ApiException(-1, "短信验证码发送失败");
        }
    }

    public static void main(String[] args) {
        SmsUtil.sendVerificationCodeMsg("1234", "15815006577");
    }
}
